package com.yxinsur.imc.business.service.impl;

import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxinsur.imc.business.domain.*;
import com.yxinsur.imc.business.enums.*;
import com.yxinsur.imc.business.events.publisher.BrokerCreateEventPublisher;
import com.yxinsur.imc.business.excel.BrokerRelationTemplate;
import com.yxinsur.imc.business.excel.BrokerTemplate;
import com.yxinsur.imc.business.form.*;
import com.yxinsur.imc.business.mapper.*;
import com.yxinsur.imc.business.service.IImcBrokerService;
import com.yxinsur.imc.business.vo.BrokerLeaveVo;
import com.yxinsur.imc.business.vo.BrokerRelationVo;
import com.yxinsur.imc.business.vo.BrokerRoleVo;
import com.yxinsur.imc.business.vo.BrokerVo;
import com.yxinsur.imc.common.core.domain.entity.SysDictData;
import com.yxinsur.imc.common.core.domain.entity.SysOrg;
import com.yxinsur.imc.common.exception.BaseException;
import com.yxinsur.imc.common.exception.BusinessException;
import com.yxinsur.imc.common.exception.CustomException;
import com.yxinsur.imc.common.utils.DateUtils;
import com.yxinsur.imc.common.utils.SecurityUtils;
import com.yxinsur.imc.common.utils.StringUtils;
import com.yxinsur.imc.system.mapper.SysDictDataMapper;
import com.yxinsur.imc.system.mapper.SysOrgMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.UncategorizedSQLException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 代理人信息Service业务层处理
 *
 * @author imc
 * @date 2021-03-18
 */
@Service
@Slf4j
public class ImcBrokerServiceImpl extends ServiceImpl<ImcBrokerMapper, ImcBroker> implements IImcBrokerService {

    private static final Logger logger = LoggerFactory.getLogger(ImcBrokerServiceImpl.class);
    @Autowired
    private ImcBrokerMapper imcBrokerMapper;
    @Autowired
    private ImcBrokerRoleMapper imcBrokerRoleMapper;
    @Autowired
    private ImcBrokerRelationMapper imcBrokerRelationMapper;
    @Autowired
    private ImcTeamMapper imcTeamMapper;
    @Autowired
    private SysOrgMapper sysOrgMapper;
    @Autowired
    private ImcRoleMapper imcRoleMapper;
    @Autowired
    private SysDictDataMapper dictDataMapper;
    @Autowired
    private BrokerCreateEventPublisher brokerCreateEventPublisher;

    @Autowired
    private ImcOrderMapper imcOrderMapper;

    @Value("${baoxianxia.url}")
    private String baoxianxiaUrl;

    /**
     * 查询代理人信息
     *
     * @param id 代理人信息ID
     * @return 代理人信息
     */
    @Override
    public BrokerVo selectImcBrokerById(String id) {
        BrokerSearchForm searchForm = new BrokerSearchForm();
        searchForm.setId(Long.valueOf(id));
        searchForm.setTenantId(SecurityUtils.getTenantId());
        String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
        String[] split = authOrgIds.split(",");
        List<String> orgStrList = Arrays.asList(split);
        List<Long> collect = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
        searchForm.setOrgIds(collect);
        ArrayList<BrokerVo> brokerVos = imcBrokerMapper.selectImcBrokerBaseInfo(searchForm);
        if (CollectionUtils.isEmpty(brokerVos)) {
            return null;
        }
        BrokerVo brokerVo = brokerVos.get(0);
        List<BrokerRoleVo> brokerRoleVos = imcBrokerRoleMapper.selectListByBrokerId(Long.valueOf(id));
        if (CollectionUtils.isEmpty(brokerRoleVos)) {//职级为空
            return brokerVo;
        }
        String roleName = "";
        for (BrokerRoleVo brokerRoleVo : brokerRoleVos) {
            roleName += brokerRoleVo.getRoleName() + ",";
        }
        ImcTeam team = imcTeamMapper.selectImcTeamById(brokerVo.getRootTeamId());
        brokerVo.setRootTeamName(team.getTeamName());
        String substring = roleName.substring(0, roleName.length() - 1);
        brokerVo.setBrokerRoleName(substring);
        brokerVo.setRoles(brokerRoleVos);
        return brokerVo;
    }

    /**
     * 查询代理人信息列表
     *
     * @param brokerForm 代理人信息
     * @return 代理人信息
     */
    @Override
    public List<ImcBroker> selectImcBrokerList(BrokerSearchForm brokerForm) {
        brokerForm.setStatus("Y");
        brokerForm.setTenantId(SecurityUtils.getTenantId());
        return imcBrokerMapper.selectImcBrokerList(brokerForm);
    }

    /**
     * 新增代理人信息
     *
     * @param broker 代理人信息
     * @return 结果
     */
    @Transactional
    @Override
    public int insertImcBroker(BrokerSaveForm broker) {
        try {
            Long tenantId = SecurityUtils.getTenantId();
            //保存代理人基本信息
            ImcBroker imcBroker = new ImcBroker();
            //同租户下工号唯一
            if(!checkBrokerCode(broker.getBrokerCode())){
                throw new BusinessException("同租户下已存在该工号");
            }
            BeanUtils.copyProperties(broker, imcBroker);
            imcBroker.setTenantId(String.valueOf(tenantId));
            imcBroker.setStatus("Y");
            imcBrokerMapper.insertImcBroker(imcBroker);

            //保存代理人角色信息
            List<BrokerRoleForm> roles = broker.getRoles();
            for (BrokerRoleForm role : roles) {
                ImcBrokerRole imcBrokerRole = new ImcBrokerRole();
                BeanUtils.copyProperties(role, imcBrokerRole);
                imcBrokerRole.setBrokerId(imcBroker.getId());
                imcBrokerRole.setBrokerRoleStart(role.getBrokerRoleStart());
                imcBrokerRole.setTenantId(tenantId);
                imcBrokerRoleMapper.insertImcBrokerRole(imcBrokerRole);
            }
            //保存代理人血缘信息
            Long brokerUpId = broker.getBrokerUpId();
            if (StringUtils.isNull(brokerUpId)) {
                ImcBrokerRelation brokerRelation = new ImcBrokerRelation();
                brokerRelation.setBrokerId(imcBroker.getId());
                brokerRelation.setBrokerUpId(0L);
                brokerRelation.setAncestors("0");
                brokerRelation.setStatus("Y");
                brokerRelation.setCreateId(SecurityUtils.getUsername());
                brokerRelation.setUpdateId(SecurityUtils.getUsername());
                brokerRelation.setTenantId(String.valueOf(tenantId));
                return imcBrokerRelationMapper.insertImcBrokerRelation(brokerRelation);
            } else {
                ImcBrokerRelation imcBrokerRelation = new ImcBrokerRelation();
                imcBrokerRelation.setBrokerId(imcBroker.getId());
                ImcBrokerRelation upRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(brokerUpId);
                imcBrokerRelation.setAncestors(upRelation.getAncestors() + "," + upRelation.getBrokerId());
                imcBrokerRelation.setBrokerUpId(brokerUpId);
                imcBrokerRelation.setTenantId(String.valueOf(tenantId));
                imcBrokerRelationMapper.insertImcBrokerRelation(imcBrokerRelation);
            }
            //查询推荐关系
            imcBrokerRelationMapper.getBrokerUpBrokersByBrokerId(broker.getId());
            //发布代理人信息录入成功事件
            brokerCreateEventPublisher.pushlish("代理人信息录入成功", imcBroker);
        } catch (UncategorizedSQLException e) {
            throw new BusinessException("推荐关系发生错误，请检查");
        } catch (Exception e) {
            logger.debug(e.getMessage());
            throw new BusinessException("代理人信息保存错误，错误信息："+e.getMessage());
        }
        return 1;
    }

    /**
     * 修改代理人信息
     *
     * @param broker 代理人信息
     * @return 结果
     */
    @Transactional
    @Override
    public int updateImcBroker(BrokerSaveForm broker) {
        try {
            //保存代理人基本信息
            Long tenantId = SecurityUtils.getTenantId();
            String username = SecurityUtils.getUsername();
            Long brokerId = broker.getId();
            ImcBroker imcBroker = new ImcBroker();
            BeanUtils.copyProperties(broker, imcBroker);
            imcBrokerMapper.updateImcBroker(imcBroker);

            //保存代理人角色信息
            QueryWrapper<ImcBrokerRole> brokerRoleQueryWrapper = new QueryWrapper<>();
            brokerRoleQueryWrapper.eq("broker_id",brokerId);
            brokerRoleQueryWrapper.eq("is_deleted", IsDeletedEnum.N.getCode());
            List<ImcBrokerRole> brokerRoles = imcBrokerRoleMapper.selectList(brokerRoleQueryWrapper);
            for (ImcBrokerRole brokerRole : brokerRoles) {
                imcBrokerRoleMapper.deleteImcBrokerRoleById(brokerRole.getId());
            }
            List<BrokerRoleForm> roles = broker.getRoles();
            for (BrokerRoleForm role : roles) {
                ImcBrokerRole imcBrokerRole = new ImcBrokerRole();
                BeanUtils.copyProperties(role, imcBrokerRole);
                imcBrokerRole.setBrokerId(brokerId);
                imcBrokerRole.setTenantId(tenantId);
                imcBrokerRole.setCreateId(username);
                imcBrokerRole.setCreateTime(DateUtils.getNowDate());
                imcBrokerRole.setUpdateId(username);
                imcBrokerRole.setUpdateTime(DateUtils.getNowDate());
                imcBrokerRoleMapper.insertImcBrokerRole(imcBrokerRole);

            }
            //保存代理人血缘信息
            Long brokerUpId = broker.getBrokerUpId();
            if (!StringUtils.isNull(brokerUpId)) {
                ImcBrokerRelation imcBrokerRelation = new ImcBrokerRelation();
                imcBrokerRelation.setBrokerId(brokerId);
                imcBrokerRelation.setBrokerUpId(brokerUpId);
                ImcBrokerRelation oldBrokerRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(brokerId);
                ImcBrokerRelation newBrokerRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(brokerUpId);
                String newAncestors = newBrokerRelation.getAncestors() + "," + newBrokerRelation.getBrokerId();
                String oldAncestors = oldBrokerRelation.getAncestors();
                imcBrokerRelation.setAncestors(newAncestors);
                imcBrokerRelation.setId(oldBrokerRelation.getId());
                updateChildrenRelation(imcBrokerRelation.getBrokerId(), newAncestors, oldAncestors);
                imcBrokerRelation.setUpdateTime(DateUtils.getNowDate());
                checkBrokerRelation(imcBrokerRelation);
                imcBrokerRelationMapper.updateImcBrokerRelation(imcBrokerRelation);
            }
            //查询推荐关系
            imcBrokerRelationMapper.getBrokerUpBrokersByBrokerId(broker.getId());

            //发布代理人信息录入成功事件
            brokerCreateEventPublisher.pushlish("代理人信息录入成功", imcBroker);
        } catch (UncategorizedSQLException e) {
            throw new BusinessException("推荐关系发生错误，请检查");
        } catch (Exception e) {
            logger.debug(e.getMessage());
            throw new BusinessException("代理人信息保存错误："+e.getMessage());
        }


        return 1;
    }

    private void checkBrokerRelation(ImcBrokerRelation imcBrokerRelation) {
        String ancestors = imcBrokerRelation.getAncestors();
        String[] brokerIds = ancestors.split(",");
        Long brokerId = imcBrokerRelation.getBrokerId();
        for (String id : brokerIds) {
            if(id.equals(String.valueOf(brokerId))){
                throw new BusinessException("推荐关系发生错误");
            }
        }
    }

    /**
     * 修改子关系
     *
     * @param brokerId
     * @param newAncestors
     * @param oldAncestors
     */
    private void updateChildrenRelation(Long brokerId, String newAncestors, String oldAncestors) {
        List<ImcBrokerRelation> children = imcBrokerRelationMapper.selectChildrenRelationByBrokerId(brokerId);
        for (ImcBrokerRelation child : children) {
            child.setAncestors(child.getAncestors().replace(oldAncestors, newAncestors));
            imcBrokerRelationMapper.updateImcBrokerRelation(child);
        }
    }

    /**
     * 批量删除代理人信息
     *
     * @param ids 需要删除的代理人信息ID
     * @return 结果
     */
    @Override
    public int deleteImcBrokerByIds(Long[] ids) {
        return imcBrokerMapper.updateImcBrokerLose(ids);
    }

    /**
     * 删除代理人信息信息
     *
     * @param id 代理人信息ID
     * @return 结果
     */
    @Override
    public int deleteImcBrokerById(String id) {
        ImcBroker imcBroker = imcBrokerMapper.selectById(id);
        imcBroker.setIsDeleted(id);
        return imcBrokerMapper.updateImcBroker(imcBroker);
    }

    @Transactional
    @Override
    public int insertImcBrokerDimission(BrokerDimissionForm brokerForm) {
        //保单转移
        if(brokerForm.getOrderHeirId()!=null){
            ImcOrder imcOrder = new ImcOrder();
            imcOrder.setBrokerId(brokerForm.getOrderHeirId());
            imcOrder.setUpdateId(SecurityUtils.getUsername());
            imcOrder.setUpdateTime(DateUtils.getNowDate());
            QueryWrapper<ImcOrder> wrapper = new QueryWrapper<>();
            wrapper.eq("broker_id",brokerForm.getId());
            imcOrderMapper.update(imcOrder,wrapper);
        }

        //修改代理人信息状态为离职
        Long brokerId = brokerForm.getId();
        ImcBroker imcBroker = new ImcBroker();
        imcBroker.setId(brokerId);
        imcBroker.setLeaveDate(brokerForm.getLeaveDate());
        imcBroker.setLeaveCause(brokerForm.getLeaveCause());
        imcBroker.setOrderHeirId(brokerForm.getOrderHeirId());
        imcBroker.setStatus("N");
        imcBroker.setUpdateId(SecurityUtils.getUsername());
        imcBroker.setUpdateTime(DateUtils.getNowDate());
        return imcBrokerMapper.updateImcBroker(imcBroker);
    }

    //撤销离职状态
    @Override
    public int cancelDimission(Long brokerId) {
        ImcBroker imcBroker = new ImcBroker();
        imcBroker.setId(brokerId);
        imcBroker.setLeaveDate(null);
        imcBroker.setLeaveCause(null);
        imcBroker.setStatus("Y");
        return imcBrokerMapper.updateImcBroker(imcBroker);
    }

    @Override
    public boolean checkBrokerCertiCode(String certiCode) {
        Long tenantId = SecurityUtils.getTenantId();
        List<ImcBroker> imcBrokerList = imcBrokerMapper.selectImcBrokerByCertiCode(certiCode,tenantId);
        if(CollectionUtils.isEmpty(imcBrokerList)){//不存在 可用这个工号
            return true;
        }
        return false;//不为null  存在该代理人 工号已占用
    }

    /**
     * 代理人删除校验
     * @param ids
     */
    @Override
    public void deleteCheck(Long[] ids) {
        StringBuilder errorStr = new StringBuilder();
        List<BrokerRelationVo> brokerRelationList = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerIds(ids);
        List<ImcBroker> imcBrokers = imcBrokerMapper.selectBatchIds(new ArrayList<>(Arrays.asList(ids)));
        Map<Long, String> brokerMap = imcBrokers.stream().collect(Collectors.toMap(ImcBroker::getId, ImcBroker::getFullName));
        //上下级关系
        for (BrokerRelationVo relation : brokerRelationList) {
            if(0!=relation.getBrokerUpId() || null != relation.getBrokerDownId()){
                errorStr.append("代理人[").append(brokerMap.get(relation.getBrokerId())).append("],存在上级或下级关系，请先修改");
                break;
            }
        }
        //出单的代理人
        QueryWrapper<ImcOrder> wrapper = new QueryWrapper<>();
        wrapper.in("broker_id",ids);
        wrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
        wrapper.eq("tenant_id",SecurityUtils.getTenantId());
        List<ImcOrder> imcOrders = imcOrderMapper.selectList(wrapper);
        List<SysDictData> dictData = dictDataMapper.selectDictDataByType("order_status_code");
        Map<String, String> dictMap = dictData.stream().collect(Collectors.toMap(SysDictData::getDictValue, SysDictData::getDictLabel));
        if(!CollectionUtils.isEmpty(imcOrders)){
            for (ImcOrder imcOrder : imcOrders) {
                errorStr.append("代理人[").append(brokerMap.get(imcOrder.getBrokerId())).append("]存在"+dictMap.get(imcOrder.getOrderStatusCode())+"保单,保单号：[").append(imcOrder.getPolicyCode()).append("]，请先转移保单;");
            }
        }
        if(errorStr.length()>0){
            throw new BusinessException(errorStr.toString());
        }

    }

    @Override
    public List<BrokerLeaveVo> selectImcBrokerDimissionList(BrokerDimissionSearchForm brokerForm) {
        String authOrgIds = SecurityUtils.getLoginUser().getAuthOrgIds();
        String[] split = authOrgIds.split(",");
        List<String> orgStrList = Arrays.asList(split);
        List<Long> orgIds = orgStrList.stream().map(Long::parseLong).collect(Collectors.toList());
        Long tenantId=SecurityUtils.getTenantId();
        return imcBrokerMapper.selectBrokerDimissionList(brokerForm,orgIds,tenantId);
    }

    /**
     * 导入代理人信息
     *
     * @param brokerList    用户数据列表
     * @param updateSupport 是否更新支持，如果已存在，则进行更新数据
     * @param operName      操作用户
     * @return 结果
     */
    @Transactional
    @Override
    public String importBroker(List<BrokerTemplate> brokerList, boolean updateSupport, String operName) {
        Long tenantId = SecurityUtils.getTenantId();
        int successNum = 0;
        int failureNum = 0;
        StringBuilder successMsg = new StringBuilder();
        StringBuilder failureMsg = new StringBuilder();
        for (BrokerTemplate broker : brokerList) {
            try {
                ImcBroker imcBroker = new ImcBroker();
                BeanUtils.copyProperties(broker, imcBroker);
                String teamName = broker.getTeamName();
                ImcTeam team = imcTeamMapper.selectByTeamName(teamName,tenantId);
                imcBroker.setTeamId(team.getId());
                successNum++;
                imcBroker.setTenantId(String.valueOf(tenantId));
                Date leaveDate = imcBroker.getLeaveDate();
                if (StringUtils.isNull(leaveDate)) {
                    imcBroker.setStatus("Y");
                } else {
                    imcBroker.setStatus("N");
                }
                imcBrokerMapper.insertImcBroker(imcBroker);

            } catch (Exception e) {
                failureNum++;
                String msg = "<br/>" + failureNum + "、账号 " + broker.getFullName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                log.error(msg, e);
            }
        }
        String message = saveRelation(brokerList, 0);
        if (!"success".equals(message)) {
            failureNum++;
            failureMsg.append("<br/>" + message);
        }
        if (failureNum > 0) {
            failureMsg.insert(0, "很抱歉，导入失败！共 " + failureNum + " 条数据格式不正确，错误如下：");
            throw new CustomException(failureMsg.toString());
        } else {
            //保存代理人信息
            successMsg.insert(0, "恭喜您，数据已全部导入成功！共 " + successNum + " 条，数据如下：");
        }
        return successMsg.toString();
    }

    public String saveRelation(List<BrokerTemplate> brokerList, int count) {
        if (CollectionUtils.isEmpty(brokerList)) {
            return "success";
        }
        if (count == 100) {
            String brokerName = "";
            for (BrokerTemplate brokerTemplate : brokerList) {
                brokerName += brokerTemplate.getFullName() + ":" + brokerTemplate.getBrokerCode() + ",";
            }
            return "代理人" + brokerName + "推荐关系出错，请检查";
        }
        Long tenantId = SecurityUtils.getTenantId();
        ArrayList<BrokerTemplate> catchList = new ArrayList<>();
        for (BrokerTemplate brokerTemplate : brokerList) {
            try {
                String brokerCode = brokerTemplate.getBrokerCode();
                ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerByCode(brokerCode, tenantId);
                String relationCode = brokerTemplate.getRelationCode();
                if (StringUtils.isEmpty(relationCode)) {
                    ImcBrokerRelation brokerRelation = new ImcBrokerRelation();
                    brokerRelation.setBrokerId(imcBroker.getId());
                    brokerRelation.setBrokerUpId(0L);
                    brokerRelation.setAncestors("0");
                    brokerRelation.setStatus("Y");
                    brokerRelation.setCreateId(SecurityUtils.getUsername());
                    brokerRelation.setUpdateId(SecurityUtils.getUsername());
                    brokerRelation.setTenantId(String.valueOf(tenantId));
                    imcBrokerRelationMapper.insertImcBrokerRelation(brokerRelation);
                } else {
                    ImcBroker brokerUp = imcBrokerMapper.selectImcBrokerByCode(relationCode, tenantId);
                    //存在上级，查询relation表，表中有值就insert  没有值就catch  递归
                    if(StringUtils.isNull(brokerUp)){
                        throw new BusinessException("请检查工号为:" + relationCode + "的代理人是否存在表中或系统中!" );
                    }
                    ImcBrokerRelation upRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(brokerUp.getId());
                    ImcBrokerRelation brokerRelation = new ImcBrokerRelation();
                    brokerRelation.setBrokerId(imcBroker.getId());
                    brokerRelation.setAncestors(upRelation.getAncestors() + "," + upRelation.getBrokerId());
                    brokerRelation.setBrokerUpId(brokerUp.getId());
                    brokerRelation.setCreateId(SecurityUtils.getUsername());
                    brokerRelation.setUpdateId(SecurityUtils.getUsername());
                    brokerRelation.setTenantId(String.valueOf(tenantId));
                    imcBrokerRelationMapper.insertImcBrokerRelation(brokerRelation);
                }
            }
            catch (BusinessException e) {
                throw new BusinessException(e.getMessage());
            }
            catch (BaseException e) {
                catchList.add(brokerTemplate);
            }
        }
        count++;
        return saveRelation(catchList, count);
    }

    @Override
    public HashMap<String, Object> checkImportBroker(List<BrokerTemplate> brokerList) {
        HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("flag", true);
        if (StringUtils.isNull(brokerList) || brokerList.size() == 0) {
            returnMap.put("flag", false);
            returnMap.put("message", "导入代理人数据不能为空！");
            return returnMap;
        }
        int failureNum = 0;
        StringBuilder failureMsg = new StringBuilder();

        boolean codeFlag = false;
        HashMap<String,List<String>> nameMap = new HashMap<String,List<String>>();
        for (int i = 0; i < brokerList.size(); i++) {
            BrokerTemplate broker = brokerList.get(i);
            //必填信息校验
            if(StringUtils.isEmpty(broker.getIndex())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、序号不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getTeamName())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、团队信息不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getFullName())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、姓名不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getCertiType())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、证件类型不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getCertiCode())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、证件号不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getGender())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、性别不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getPhone())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、电话信息不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getQuafNo())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、职业证号不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isNull(broker.getEmployDate())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、入职日期不能为空");
                returnMap.put("message", failureMsg.toString());
            }
            if(StringUtils.isEmpty(broker.getBrokerCode())){
                returnMap.put("flag", false);
                failureMsg.append("<br/>" + failureNum + "、代理人工号不能为空");
                returnMap.put("message", failureMsg.toString());
            }

            try {
                //验证表格内是否存在相同工号信息
                if(nameMap.containsKey(broker.getBrokerCode())){
                    codeFlag=true;
                    List<String> nameAddList = nameMap.get(broker.getBrokerCode());
                    nameAddList.add(broker.getFullName());
                    nameMap.put(broker.getBrokerCode(),nameAddList);
                }else{
                    ArrayList<String> nameList = new ArrayList<>();
                    nameList.add(broker.getFullName());
                    nameMap.put(broker.getBrokerCode(),nameList);
                }
                // 验证是否存在这个代理人
                QueryWrapper<ImcBroker> wrapper = new QueryWrapper<>();
                wrapper.eq("broker_code", broker.getBrokerCode());
                wrapper.eq("tenant_id", SecurityUtils.getTenantId());
                wrapper.eq("is_deleted",IsDeletedEnum.N.getCode());
                ImcBroker b = imcBrokerMapper.selectOne(wrapper);
                if (!StringUtils.isNull(b)) {
                    failureNum++;
                    returnMap.put("flag", false);
                    failureMsg.append("<br/>" + failureNum + "、代理人 " + broker.getFullName() + "工号已存在");
                    returnMap.put("message", failureMsg.toString());
                    continue;
                }
                //验证团队信息是否存在
                String teamName = broker.getTeamName();
                ImcTeam team = imcTeamMapper.selectByTeamName(teamName,SecurityUtils.getTenantId());

                if (StringUtils.isNull(team)) {
                    failureNum++;
                    returnMap.put("flag", false);
                    failureMsg.append("<br/>" + failureNum + "、团队 :" + broker.getTeamName() + "信息不存在，请检查");
                    returnMap.put("message", failureMsg.toString());
                }
            } catch (Exception e) {
                failureNum++;
                returnMap.put("flag", false);
                String msg = "<br/>" + failureNum + "、账号 " + broker.getFullName() + " 导入失败：";
                failureMsg.append(msg + e.getMessage());
                returnMap.put("message", failureMsg.toString());
                log.error(msg, e);
            }
        }
        //表格中重复code遍历
        if(codeFlag){
            String msg="";
            for (Map.Entry<String, List<String>> entry : nameMap.entrySet()) {
                if(entry.getValue().size()>1){
                    msg += "<br/> 导入表格数据中   工号："  +entry.getKey()+ "存在相同代理人： " + entry.getValue().toString();
                }
            }
            returnMap.put("flag", false);
            failureMsg.append(msg);
            returnMap.put("message", failureMsg.toString());
        }
        return returnMap;
    }

    @Override
    public ArrayList<BrokerVo> selectImcBrokerBaseInfo(BrokerSearchForm broker) {
        broker.setTenantId(SecurityUtils.getTenantId());
        ArrayList<BrokerVo> brokerVos = imcBrokerMapper.selectImcBrokerBaseInfo(broker);
        for (BrokerVo brokerVo : brokerVos) {
            ImcTeam team = imcTeamMapper.selectImcTeamById(brokerVo.getRootTeamId());
            brokerVo.setRootTeamName(team.getTeamName());
        }
        return brokerVos;
    }

    /**
     * 代理人锁定状态
     *
     * @param id
     * @param lock
     */
    @Override
    public void lockBroker(Long id, String lock) {
        ImcBroker imcBroker = new ImcBroker();
        imcBroker.setId(id);
        imcBroker.setIsLocked(lock);
        imcBrokerMapper.updateImcBroker(imcBroker);
    }

    /**
     * 代理人工号重复校验
     * @param brokerCode
     * @return
     */
    @Override
    public boolean checkBrokerCode(String brokerCode) {
        ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerByCode(brokerCode, SecurityUtils.getTenantId());
        if(imcBroker==null){//不存在 可用这个工号
            return true;
        }
        return false;//不为null  存在该代理人 工号已占用
    }

    @Override
    public List<ImcBroker> selectBrokerByTeamId(Long teamId) {
        BrokerSearchForm brokerSearchForm = new BrokerSearchForm();
        brokerSearchForm.setTenantId(SecurityUtils.getTenantId());
        brokerSearchForm.setTeamId(teamId.toString());
        return imcBrokerMapper.selectImcBrokerList(brokerSearchForm);
    }

    /**
     * 获取当前租户下代理人最大工号
     * @return
     */
    @Override
    public String getMaxBrokerCode() {
        return imcBrokerMapper.getMaxBrokerCode(SecurityUtils.getTenantId());
    }

    @Override
    public HashMap<String, Object> checkImportRelation(List<BrokerRelationTemplate> brokerRelationList) {
        HashMap<String, Object> returnMap = new HashMap<>();
        returnMap.put("flag", true);
        if (StringUtils.isNull(brokerRelationList) || brokerRelationList.size() == 0) {
            returnMap.put("flag", false);
            returnMap.put("message", "导入推荐关系数据不能为空！");
            return returnMap;

        }
        for (BrokerRelationTemplate brokerRelationTemplate : brokerRelationList) {
            String brokerCode = brokerRelationTemplate.getBrokerCode();
            if(StringUtils.isNotEmpty(brokerCode.trim()) && checkBrokerCode(brokerCode)){
                returnMap.put("flag",false);
                returnMap.put("message","工号"+brokerCode+",姓名"+brokerRelationTemplate.getFullName()+"不存在,请检查");
                return returnMap;
            }
            if(StringUtils.isNotEmpty(brokerRelationTemplate.getRelationCode()) && checkBrokerCode(brokerRelationTemplate.getRelationCode())){
                returnMap.put("flag",false);
                returnMap.put("message","工号"+brokerCode+",姓名"+brokerRelationTemplate.getFullName()+"的推荐人不存在,请检查");
                return returnMap;
            }
            if(StringUtils.isNotEmpty(brokerRelationTemplate.getRelationCode())){
                //查询brokerupid在表中的子集 如果有当前这个人就返回提示推荐关系冲突
                ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerByCode(brokerCode, SecurityUtils.getTenantId());
                ImcBroker imcBrokerUp = imcBrokerMapper.selectImcBrokerByCode(brokerRelationTemplate.getRelationCode(), SecurityUtils.getTenantId());
                List<ImcBrokerRelation> children = imcBrokerRelationMapper.selectChildrenRelationByBrokerId(imcBrokerUp.getId());
                for (ImcBrokerRelation child : children) {
                    if(child.getBrokerId().equals(imcBroker.getId())){
                        returnMap.put("flag",false);
                        returnMap.put("message","工号"+brokerCode+",姓名"+brokerRelationTemplate.getFullName()+"的推荐人"+brokerRelationTemplate.getRelationName()+"存在间接或直接上下级关系，请检查");
                        return returnMap;
                    }
                }
            }
        }
        return returnMap;
    }

    @Transactional
    @Override
    public String importRelation(List<BrokerRelationTemplate> brokerRelationList) {
        try {
            for (BrokerRelationTemplate brokerRelationTemplate : brokerRelationList) {
                ImcBroker imcBroker = imcBrokerMapper.selectImcBrokerByCode(brokerRelationTemplate.getBrokerCode(), SecurityUtils.getTenantId());
                //保存代理人血缘信息
                String relationCode = brokerRelationTemplate.getRelationCode();
                if (!StringUtils.isEmpty(relationCode)) {
                    ImcBroker brokerUp = imcBrokerMapper.selectImcBrokerByCode(relationCode, SecurityUtils.getTenantId());
                    ImcBrokerRelation imcBrokerRelation = new ImcBrokerRelation();
                    imcBrokerRelation.setBrokerId(imcBroker.getId());
                    imcBrokerRelation.setBrokerUpId(brokerUp.getId());
                    ImcBrokerRelation oldBrokerRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(imcBroker.getId());
                    ImcBrokerRelation newBrokerRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(brokerUp.getId());
                    String newAncestors = newBrokerRelation.getAncestors() + "," + newBrokerRelation.getBrokerId();
                    String oldAncestors = oldBrokerRelation.getAncestors();
                    imcBrokerRelation.setAncestors(newAncestors);
                    imcBrokerRelation.setId(oldBrokerRelation.getId());
                    updateChildrenRelation(imcBrokerRelation.getBrokerId(), newAncestors, oldAncestors);
                    imcBrokerRelation.setUpdateTime(DateUtils.getNowDate());
                    imcBrokerRelationMapper.updateImcBrokerRelation(imcBrokerRelation);
                }else{
                    ImcBrokerRelation oldBrokerRelation = imcBrokerRelationMapper.selectImcBrokerRelationByBrokerId(imcBroker.getId());
                    oldBrokerRelation.setBrokerId(imcBroker.getId());
                    oldBrokerRelation.setBrokerUpId(0L);
                    oldBrokerRelation.setAncestors("0");
                    oldBrokerRelation.setStatus("Y");
                    oldBrokerRelation.setCreateId(SecurityUtils.getUsername());
                    oldBrokerRelation.setUpdateId(SecurityUtils.getUsername());
                    oldBrokerRelation.setTenantId(String.valueOf(SecurityUtils.getTenantId()));
                    imcBrokerRelationMapper.updateImcBrokerRelation(oldBrokerRelation);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("代理人推荐关系导入异常，请检查");
        }

        return "代理人推荐关系保存成功";
    }

    /**
     * 查询在线入司代理人
     * @param fullName
     * @param orgId
     * @return
     */
    @Override
    public List<ApiBrokerOnline> choiceOnlineList(String fullName, Long orgId) {
        HashMap<String, Object> param = new HashMap<>();
        param.put("brokerName",fullName);
        ArrayList<String> orgGuids = new ArrayList<>();
        orgGuids.add("-1");
        if(orgId!=null){
            SysOrg sysOrg = sysOrgMapper.selectOrgById(orgId);
            if(!StringUtils.isEmpty(sysOrg.getOrgGuid())){
                orgGuids.add(sysOrg.getOrgGuid());
            }
        }else{
            throw new BusinessException("选择机构为空，请检查");
        }


        param.put("orgNoList",orgGuids);
        String json = JSON.toJSONString(param);
        logger.info("请求在线入司人员列表参数：{}",json);
        String returnJson = HttpUtil.post(baoxianxiaUrl,json);

        logger.info("请求在线入司人员列表结果：{}",returnJson);
        if(StringUtils.isNotBlank(returnJson)){
            JSONObject result = JSONObject.parseObject(returnJson);
            if(result!=null && result.getIntValue("code")==10000){
                List<ApiBrokerOnline> apiBrokerOnlines = JSONArray.parseArray(result.getString("data"), ApiBrokerOnline.class);
                for (ApiBrokerOnline apiBrokerOnline : apiBrokerOnlines) {
                    apiBrokerOnline.setGender(GenderType.getValueByKeyName(apiBrokerOnline.getGender()));
                    apiBrokerOnline.setCertiType(PapersType.getValueByKeyName(apiBrokerOnline.getCertiType()));
                    apiBrokerOnline.setPoliticalStatus(PolittcalStatus.getValueByKeyName(apiBrokerOnline.getPoliticalStatus()));
                    apiBrokerOnline.setEducationId(EducationEnum.getValueByKeyName(apiBrokerOnline.getEducationId()));
                    apiBrokerOnline.setNationId(NationEnum.getValueByKeyName(apiBrokerOnline.getNationId()));
                    //推荐人brokerId
                    ImcBroker inviter = imcBrokerMapper.selectImcBrokerByCode(apiBrokerOnline.getInviterCode(), SecurityUtils.getTenantId());
                    if(inviter!=null){
                        apiBrokerOnline.setInviterId(String.valueOf(inviter.getId()));
                        //推荐人teamId
                        apiBrokerOnline.setInviterTeamId(String.valueOf(inviter.getTeamId()));
                    }
                }
                return apiBrokerOnlines;
            }else{//测试代码 虚假数据
                ArrayList<ApiBrokerOnline> apiBrokerOnlines = new ArrayList<>();
                ApiBrokerOnline apiBrokerOnline = new ApiBrokerOnline();
                apiBrokerOnline.setUserId("ZXRS01");
                apiBrokerOnline.setBrokerName("在线入司");
                apiBrokerOnline.setGender("男");
                apiBrokerOnline.setNationId("汉族");
                apiBrokerOnline.setCertiType("身份证");
                apiBrokerOnline.setCertiCode("202108241747");
                apiBrokerOnline.setPoliticalStatus("党员");
                apiBrokerOnline.setRsdResidence("北京市");
                apiBrokerOnline.setAddressData("北京市朝阳区朝外大街");
                apiBrokerOnline.setEducationId("本科");
                apiBrokerOnline.setGradSchool("北京大学");
                apiBrokerOnline.setUrContactNm("海苔");
                apiBrokerOnline.setUrContactMb("18547496548");
                apiBrokerOnline.setBankAccount("85214796321354787931");
                apiBrokerOnline.setOpenBank("建设银行");
                apiBrokerOnline.setInviterCode("TZ00091");
                //推荐人brokerId
                ImcBroker inviter = imcBrokerMapper.selectImcBrokerByCode(apiBrokerOnline.getInviterCode(), 130L);
                apiBrokerOnline.setInviterId(String.valueOf(inviter.getId()));
                //推荐人teamId
                apiBrokerOnline.setInviterTeamId(String.valueOf(inviter.getTeamId()));
                apiBrokerOnline.setMobile("15832529685");
                apiBrokerOnlines.add(apiBrokerOnline);
                return apiBrokerOnlines;
            }
        }
        return new ArrayList<>();
    }


}
